<template>
  <view class="container">
    <view class="form">
      <view class="form-item">
        <text class="label">姓名</text>
        <input type="text" style="width: 80vw;" placeholder="请输入姓名" v-model="name" />
      </view>
      <view class="form-item">
        <text class="label">电话号码</text>
        <input type="text" style="width: 80vw;" placeholder="请输入电话号码" v-model="phone" />
      </view>
      <view class="form-item">
        <text class="label" @tap="getLocation">点击获取当前位置</text>
		<input type="text" style="width: 80vw;" placeholder="省" v-model="province" />
        <input type="text" style="width: 80vw;" placeholder="市" v-model="city" />
		<input type="text" style="width: 80vw;" placeholder="区" v-model="district" />
      </view>
      <view class="form-item">
        <text class="label">详细地址</text>
        <input type="text" style="width: 80vw;" placeholder="请输入详细地址" v-model="street" />
      </view>
    </view>
    <button class="submit-button" @click="submitAddress">提交</button>
  </view>
</template>

<script setup>
import { ref } from 'vue';

// 定义响应式数据
const address = ref('');
const name = ref('');
const phone = ref('');

const longitude=ref('');//经度
const latitude=ref('');//纬度
const province = ref(''); // 省
const city = ref(''); // 市
const district = ref(''); // 区
const street = ref(''); // 街道
const postalcode=ref('');//邮政编码


// 提交地址信息
const submitAddress = () => {
  if (!name.value || !phone.value  ||  !province.value || !city.value || !district.value) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    });
    return;
  }  
        // 确定后跳转到另一个页面，并携带 addressid
       const apiKey = 'fb7014bb45af62eac3d0a2e34eb63918'; // 替换为你的高德API Key
	   const fullAddress = `${province.value} ${city.value} ${district.value} ${street.value}`.trim();
	   if (!fullAddress) {
	   	uni.showToast({
	   		title: '请输入完整的地址',
	   		icon: 'none'
	   	});
	   	return;
	   }
	   // 调用高德地图的地理编码接口
	   uni.request({
	   	url: `https://restapi.amap.com/v3/geocode/geo?key=${apiKey}&address=${encodeURIComponent(fullAddress)}`,
	   	method: 'GET',
	   	success: (res) => {
	   		if (res.data.status === '1' && res.data.geocodes && res.data.geocodes.length > 0) {
	   			const location = res.data.geocodes[0].location.split(',');
				longitude.value=location[0];//经度
				latitude.value=location[1];//纬度
				
				const app = getApp();
				const url = app.globalData.url;
				 const addresses = {
					  custonmerid: 1, // 假设用户ID为1，实际应从登录状态获取
				     addressline1: street.value,
				     addressline2: district.value,
				     city: city.value,
				     state: province.value,
				     postalcode: postalcode.value, // 邮政编码，可选
				     latitude: parseFloat(latitude.value),
				     longitude: parseFloat(longitude.value)
				   };
					  uni.request({
					    url: url+'USER-SERVICE/customerCategory/addresseswx', 
					    method: 'POST',
					    data: addresses,
					    success(response) {
					      if (response.data === 1) {
					        uni.showToast({
					          title: "地址添加成功",
					          icon: "success"
					        });
							uni.navigateTo({
							  url: '/pages/myPage/address/address'//添加成功后自动跳地址管理
							});
					      } else {
					        uni.showToast({
					          title: "地址添加失败：" + response.data,
					          icon: "none"
					        });
					      }
					    },
					    fail(err) {
					      console.error("提交失败", err);
					      uni.showToast({
					        title: "提交失败，请检查网络",
					        icon: "none"
					      });
					    }
					  });
				
				
				
	   		} else {
	   			uni.showToast({
	   				title: '无法获取经纬度，请检查地址是否正确',
	   				icon: 'none'
	   			});
	   		}
	   	},
	   	fail: (err) => {
	   		uni.showToast({
	   			title: '请求失败，请检查网络',
	   			icon: 'none'
	   		});
	   		console.error('请求失败:', err);
	   	}
	   });

};

// 获取当前位置
const getLocation = () => {
    uni.getLocation({
        type: 'wgs84', 
        success(res) {
            console.log("经度" + res.longitude + "纬度" + res.latitude);
			longitude.value=res.longitude;
			latitude.value=res.latitude;
            // 调用高德地图反向地理编码API
            uni.request({
                url: `https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${res.longitude},${res.latitude}&key=fb7014bb45af62eac3d0a2e34eb63918&radius=1000&extensions=all`,
                success(regeoRes) {
                    console.log(regeoRes);
                    if (regeoRes.statusCode === 200 && regeoRes.data.status === "1") {
                        // 解析返回的地址信息
                        const addressComponent = regeoRes.data.regeocode.addressComponent;
                        const formattedAddress = regeoRes.data.regeocode.formatted_address;

                        console.log("详细地址信息：", addressComponent);
                        console.log("格式化地址：", formattedAddress);

                        // 提取国家、省、市、区、街道等信息
                        province.value = addressComponent.province;
                        city.value = addressComponent.city;
                        district.value = addressComponent.district;
                        street.value = addressComponent.township;
						postalcode.value=addressComponent.adcode;
                    } else {
                        uni.showToast({
                            title: "地址解析失败：" + regeoRes.data.info,
                            icon: "none"
                        });
                    }
                },
                fail(err) {
                    console.error("反向地理编码请求失败", err);
                    uni.showToast({
                        title: "反向地理编码请求失败",
                        icon: "none"
                    });
                }
            });
        },
        fail(err) {
            console.error("获取位置失败", err);
            uni.showToast({
                title: "授权失败，请开启位置权限",
                icon: "none"
            });
        }
    });
};
</script>

<style>
.container {
  padding: 20px;
}
.picker {
  padding: 10px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
}
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f5f5;
}

.form {
  width: 93%;
  max-width: 600px;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}

.label {
  font-size: 16px;
  color: #007aff;
  margin-bottom: 5px;
}

input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.picker {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  text-align: center;
}

.submit-button {
  width: 100%;
  max-width: 200px;
  background-color: #007aff;
  color: white;
  padding: 5px 20px;
  border-radius: 20px;
  margin-top: 20px;
}
</style>